const path = require("path");
const express = require("express");
const app = express();
const browserSync = require("browser-sync").create("my"); //创建browser-sync实例
const { createProxyMiddleware } = require("http-proxy-middleware")

const port = 4000;
const proxyArr = [
  {
    proxyPath: '/api',
    host: "http://localhost:6000"
  }
]

proxyArr.forEach(({ proxyPath, host }) => {
  app.use(proxyPath, createProxyMiddleware({
    target: host,
    changeOrigin: true, //是否允许跨域
    ws: false, //是否需要改变原始主机头为目标URL
    pathRewrite: {
      ["^" + proxyPath]: proxyPath
    }
  }))
})

app.use("/", express.static(path.join(__dirname))) //加载静态资源

app.get("/", (req, res) => {
  res.redirect("http://localhost:4000/pages/login.html")
})

app.listen(port, start)

function start() {
  browserSync.init({
    proxy: "http://localhost:4000",
    files: ["pages/**"],
    port: 8888, //默认3000的端口号
  }, () => {
    console.log("server run at http://localhost:5555");
  })
}